#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: get_access_token.py
# Author: ChenChangSong
# Date: 2025-09-21

"""
功能描述:获取access_token
"""
import sys
import os
import base64
from comm.common_code import *


def get_access_token(account,key):
    """获取access_token
    """
    excel_data = get_excel_data()
    url = "https://api.tapd.cn/tokens/request_token"

    payload='grant_type=client_credentials'
    # 原始字符串
    original_string = f"{account}:{key}"

    # 将字符串转换为字节
    string_bytes = original_string.encode('ascii')
    # 进行 Base64 编码
    encoded_bytes = base64.b64encode(string_bytes)
    # 将编码后的字节转换为字符串
    auth_key = encoded_bytes.decode('ascii')
    headers_urlencoded = {
        'Authorization': f'Basic {auth_key}',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': excel_data['Cookie']
    }

    logger.info(f'获取access_token↓↓↓=================================================↓↓↓')
    response_code, response = api_request(method='POST', url=url, headers=headers_urlencoded, data=payload)
    logger.info(f"响应内容: {response}")
    if response_code == 200:  # 成功
        access_token = response['data']['access_token']
        logger.info(f'获取到access_token: {access_token}')
        return response_code, access_token
    else:  # 其他错误
        logger.error(f"请求失败，响应代码: {response_code}")
        return response_code, response

if __name__ == "__main__":
    account, key = excel_data['API帐号'], excel_data['API密钥']
    get_access_token(account, key)